package com.maiyuren.fishkit.dict

data class FishDictRedirectResult(
    val template:String,
    val from: String,
    val to: String
)

class FishDictRedirect(val content: String) {
    private var template = "";
    private val kvs: MutableMap<String, String> = mutableMapOf()
    init {
        val temp = content.replace("\r\n", "\n")
        val items = temp.split("\n")
        items.forEach { kv ->
            val kv_item = kv.split(" ")
            if (kv_item != null) {
                if (kv_item[0] == "__TEMPLATE__") {
                    this.template = kv.substring(kv_item[0].length + 1)
                }
                else if (kv_item.size == 2) {
                    val kv_key = kv_item[0].trim()
                    val kv_value = kv_item[1].trim()
                    this.kvs.put(kv_key, kv_value)
                }
            }
        }
    }

    fun lookfor(word: String): FishDictRedirectResult? {
        for((key, value) in kvs) {
            if (word.startsWith(key)) {
                return FishDictRedirectResult(
                    template = template
                        .replace("\${1}", key)
                        .replace("\${2}", value),
                    from = key,
                    to = value
                )
            }
        }
        return null
    }

}